<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\ModuleInfoModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class ModuleInfoService extends BaseModelService
{
    public static function getModel()
    {
        return new ModuleInfoModel();
    }


    public static function addModule($param)
    {
        $id =  $param['id'];
        unset($param['id']);
        $origin = self::getBase($id);
        if (!empty($origin)) {
            throw new ApiException("module id is already exist", ErrnoPlus::COMMON_ERROR);
        }
        $describe_id = Helper::getUnique();
        $param['describe_id'] = $describe_id;
        DescribeInfoService::addDescribe($param);
        $item = [
            'id' => $id,
            'describe_id' => $describe_id,
        ];
        self::add($item);
    }


    public static function delModule($id)
    {
        $origin = self::getBase($id);
        if (empty($origin)) {
            throw new ApiException("module info is not exist", ErrnoPlus::COMMON_ERROR);
        }
        DescribeInfoService::delByFilter([
            'describe_id' => $origin['describe_id'],
        ]);
        self::del($id);
    }

    public static function buildCondition($filter)
    {
        return [];
    }

    public static function getListInfo($param, $pageInfo,$order = null)
    {
        $filter = static::buildCondition($param);
        $data = static::getPageList($filter, $pageInfo['page'], $pageInfo['size']);
        if (!empty($data)) {
            $describeIds = array_column($data, 'describe_id');
            $describeInfos = DescribeInfoService::getAllByFilter([
                'describe_id' => ['in', $describeIds],
            ]);
            foreach ($data as &$d) {
                $describe = Helper::filterOne($describeInfos, ['describe_id' => $d['describe_id']]);
                $d['describeName'] = $describe ? $describe['describe_name'] : '';
            }
        }
        return $data;
    }

    public static function getAllByLanguage($language)
    {
        $describeInfos = DescribeInfoService::getAllByFilter([
            'language' => $language,
        ]);
        if (empty($describeInfos)) {
            return [];
        }
        $describeIds = Helper::arraySmartUnique(array_column($describeInfos, 'describe_id'));
        $modules = self::getAllByFilter([
            'describe_id' => ['in', $describeIds],
        ]);
        foreach ($modules as &$d) {
            $describe = Helper::filterOne($describeInfos, ['describe_id' => $d['describe_id']]);
            $d['describeName'] = $describe ? $describe['describe_name'] : '';
        }
        return $modules;
    }
}
